package core;

import database.ClassDb;
import database.User;
import database.UserDb;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by jimmyhsu on 2016/12/14.
 */
public class AddSeveralUsersToClass extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userIds = req.getParameter("inputIds");
        String classId = req.getParameter("classId");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (StringUtils.isEmpty(classId)) {
            return;
        }
        if (userIds.contains(",") && userIds.contains("，")) {
            writer.print("<script>alert('逗号必须全部是半角或全角！');history.go(-1);</script>");
            return;
        }
        String[] userIdArr;
        if (userIds.contains(",")) {
            userIdArr = userIds.split(",");
        } else if (userIds.contains("，")) {
            userIdArr = userIds.split("，");
        } else {
            userIdArr = new String[]{userIds};
        }
        StringBuffer usersNotExist = new StringBuffer();
        StringBuffer usersAlreadyInClass = new StringBuffer();
        StringBuffer usersInOtherClass = new StringBuffer();
        StringBuffer result = new StringBuffer();

        for (String userId : userIdArr) {
            User user = UserDb.selectUserById(userId);
            if (user == null) {
                usersNotExist.append(userId).append("，");
            } else if (ClassDb.isUserInClass(userId, Integer.parseInt(classId))) {
                usersAlreadyInClass.append(userId).append("，");
            } else if (ClassDb.isUserInOtherClass(userId, Integer.parseInt(classId))) {
                usersInOtherClass.append(userId).append("，");
            } else {
                ClassDb.insertUserInClass(userId, Integer.parseInt(classId), 0);
            }
        }
        result.append("添加完成。");
        if (usersNotExist.length() > 0) {
            usersNotExist.substring(0, usersNotExist.length() - 1);
            result.append(usersNotExist.toString()).append("不存在。");
        }
        if (usersAlreadyInClass.length() > 0) {
            usersAlreadyInClass.substring(0, usersAlreadyInClass.length() - 1);
            result.append(usersAlreadyInClass.toString()).append("已经是班级成员，不再重复添加。");
        }
        if (usersInOtherClass.length() > 0) {
            usersInOtherClass.substring(0, usersInOtherClass.length() - 1);
            result.append(usersInOtherClass.toString()).append("已经在其他班级中，不再重复添加。");
        }
        writer.print("<script>alert(\'" + result.toString() + "\');location.href='importClassLeft.jsp?refresh=true&classId="+classId+"\';</script>\"");
    }
}
